﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace P2P_Backup
{
    public class Restore
    {        
        public static void StartRestore()
        {
            foreach (RemotePeer peer in P2PBackup.Instance.Peers)
                peer.sendCommand("RRQ", "data");
        }

        archive.Folder baseFolder;
        private Thread restoreThread;
        public Restore(archive.Folder folder)
        {
            this.baseFolder = folder;
            restoreThread = new Thread(new ThreadStart(doRestore));
            restoreThread.IsBackground = true;
            restoreThread.Start();
            ThreadPool.SetMaxThreads(10, 10);               
        }

        public void doRestore()
        {
            foreach (archive.Folder f in baseFolder.Folders)
                P2PBackup.Instance.MyArchive.addFolder(f);
            foreach (archive.File file in baseFolder.Files)
                P2PBackup.Instance.MyArchive.addFile(file);
            P2PBackup.Instance.Save();
            restoreFolder(baseFolder);
        }

        private void restoreFolder(archive.Folder folder)
        {
            foreach (archive.Folder f in baseFolder.Folders)
                restoreFolder(f);
            foreach (archive.File file in folder.Files)           
            {
                RemotePeer peer = P2PBackup.Instance.Peers.Find(p => p.Hostname.Equals(file.BackupPeer.Hostname));
                peer.sendCommand("RRQ", file.Id.ToString());                    
            }           
        }
    }
}
